#!/usr/bin/env python

import sys

sys.path.insert(0, '../')

# 加载django黄金
import os

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'meiduo_project.settings')
import django

django.setup()

from apps.goods.models import SKU
from utils.goods import get_goods_specs, get_categories, get_breadcrumb

from django.conf import settings

from apps.goods import models


def generate_static_sku_detail_html(sku_id):
    # - 1查询相关数据
    """提供商品详情页"""
    # 获取当前sku的信息
    sku = SKU.objects.get(id=sku_id)
    # 查询商品频道分类
    categories = get_categories()
    # 查询面包屑导航
    breadcrumb = get_breadcrumb(sku.category)
    # 获取规格
    specs = get_goods_specs(sku)

    # 渲染页面
    context = {
        'categories': categories,
        'breadcrumb': breadcrumb,
        'sku': sku,
        'specs': specs,
    }
    # - 2加载需要渲染模板

    from django.template import loader
    # 获取模板对象
    index_template = loader.get_template('detail.html')

    # 3把数据渲染到模板上
    index_html_data = index_template.render(context)
    # 4把渲染好的模板保存成html文件写入到指定文件
    file_path = os.path.join(os.path.dirname(settings.BASE_DIR), 'front_end_pc/goods/' + str(sku_id) + '.html')
    with open(file_path, 'w') as f:
        f.write(index_html_data)


if __name__ == '__main__':
    skus = models.SKU.objects.all()
    for sku in skus:
        print(sku.id)
        generate_static_sku_detail_html(sku.id)
